<?php

namespace App\Jobs;


use App\Libraries\Easemob\Easemob;
use App\Libraries\Tools\Msg;
use App\Models\Msg\MsgSystem;
use Illuminate\Support\Facades\Log;
use JMessage\IM\Message;
use JMessage\JMessage;

class SendSystemMsgJob extends Job
{


    private $to_ids;
    private $msg;
    private $type;
    private $ext;


    public function __construct(array $to_ids, $msg, $type, $ext=null)
    {
        $this->to_ids = $to_ids;
        $this->msg = $msg;
        $this->type = $type;//type 0-普通消息 1-红包信息 2-VIP过期信息 3-auth改变 4-agent改变 5-manager改变
        $this->ext = $ext;
    }

    /**
     * Execute the job.
     *
     * @param MsgSystem $msgSystem
     * @return bool
     * @throws \Exception
     */
    public function handle(MsgSystem $msgSystem)
    {
        try{
            if(!is_array($this->to_ids)){
                return false;
            }
            $client = new JMessage(env('JMSG_APPKEY'), env('JMSG_SECRET'));
            $message = new Message($client);
            if(is_null($this->ext)){
                $ext = ['user_id'=>6, 'type'=>$this->type];
            }else{
                $ext = $this->ext;
            }
            foreach($this->to_ids as $v){
                $msgSystem->to_id = $v;
                $msgSystem->message = $this->msg;
                $msgSystem->type = $this->type;
                $msgSystem->save();
                $msgSystem = new MsgSystem();

                $message->sendText(1, [
                    'type' => 'admin',
                    'id'   => 'beboy_6',
                    'name' => '系统消息'
                ], [
                    'type' => 'single',
                    'id'   => 'beboy_'.$v,
                ], [
                    'text' => $this->msg,
                    'extras' => $ext
                ], [
                    'notifiable' => false
                ], [
                    'offline' => true
                ]);
            }
//            $data = Easemob::singleton()->sendText(6, 'users', $this->to_ids, $this->msg, $ext);
        }catch (\Exception $e){
            throw new \Exception('send system msg Fail');
        }
//        if(!empty($data['error'])){
//            throw new \Exception('send system msg Fail');
//        }
        return true;
    }
}
